package cn.micai.base.zookeeper;

import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.IZkStateListener;
import org.I0Itec.zkclient.ZkClient;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.Watcher;

import java.util.List;

/**
 * @Auther: zhaoxinguo
 * @Date: 2018/8/24 11:05
 * @Description:
 */
public class ZkClientDemo {

    public static void main(String [] args) {
        String serverList = "";
        ZkClient zkClient = new ZkClient(serverList);

        String PATH = "/root";
        // 创建节点
        zkClient.createPersistent(PATH);

        // 创建子节点
        zkClient.create(PATH + "/child", "child znode", CreateMode.EPHEMERAL);

        // 获得子节点
        List<String> children = zkClient.getChildren(PATH);

        // 获得子节点个数
        int childCount = zkClient.countChildren(PATH);

        // 判断子节点是否存在
        zkClient.exists(PATH);

        // 写入数据
        zkClient.writeData(PATH + "/child", "hello everyone");

        // 读取节点数据
        Object obj = zkClient.readData(PATH + "/child");

        // 删除节点
        zkClient.delete(PATH + "/child");

        // 订阅子节点状态变化
        zkClient.subscribeChildChanges(PATH, new IZkChildListener() {
            @Override
            public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {

            }
        });

        // 订阅节点数据变化
        zkClient.subscribeDataChanges(PATH, new IZkDataListener() {
            @Override
            public void handleDataChange(String dataPath, Object data) throws Exception {

            }

            @Override
            public void handleDataDeleted(String dataPath) throws Exception {

            }
        });

        // 订阅连接状态的变化
        zkClient.subscribeStateChanges(new IZkStateListener() {
            @Override
            public void handleStateChanged(Watcher.Event.KeeperState state) throws Exception {

            }

            @Override
            public void handleNewSession() throws Exception {

            }
        });

    }
}
